package org.example;

import java.util.HashMap;
import java.util.Map;

public class Solution10 {

    public int subArraySum(int[] nums, int k) {

        // 记录符合条件的子数组的数量
        int count = 0;

        // 用于存储当前的前缀和
        int currentSum = 0;

        // 哈希表，用来存储前缀和及其出现次数
        Map<Integer, Integer> prefixSumCounts = new HashMap<>();
        prefixSumCounts.put(0, 1);

        // 遍历数组
        for (int num : nums) {
            // 更新当前的前缀和
            currentSum = currentSum + num;

            if (prefixSumCounts.containsKey(currentSum - k)) {
                count = count + prefixSumCounts.get(currentSum - k);
            }

            prefixSumCounts.put(currentSum, prefixSumCounts.getOrDefault(currentSum, 0) + 1);
        }

        return count;
    }

}
